//
//  HTDeliverPlaceChoiceView.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/27.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTDeliverPlaceChoiceView.h"
#import "HTAreaModel.h"
#import "HTCitiesTools.h"
#import "HTNormalCollectionCell.h"

#define boardHeight kHTScreenHeight/4*3

@interface HTDeliverPlaceChoiceView ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewY;

@property (weak, nonatomic) IBOutlet UIView *historyView;
@property (weak, nonatomic) IBOutlet UIButton *historyFirstButton;
@property (weak, nonatomic) IBOutlet UIButton *historySecondButton;

@property (weak, nonatomic) IBOutlet UIButton *historyThirdButton;

//省市区
@property (weak, nonatomic) IBOutlet UILabel *provinceLabel;
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
@property (weak, nonatomic) IBOutlet UILabel *areaLabel;

//collection
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;

//空白部分
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *animateTop;

//数据处理
@property (nonatomic,strong) NSArray *provinces;//省
@property (nonatomic,strong) NSArray *cities;//市
@property (nonatomic,strong) NSArray *areas;//区

@property (nonatomic,strong) HTCitiesTools *citiesTools;

@property (nonatomic,strong) NSArray <HTAreaModel *>*dataSource;
@property (nonatomic,strong) NSMutableArray *historyPlistData;
@property (weak, nonatomic) IBOutlet UIView *boardView;

@end


@implementation HTDeliverPlaceChoiceView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) {
        self = [[[NSBundle mainBundle] loadNibNamed:@"HTDeliverPlaceChoiceView" owner:self options:nil] lastObject];
        self.frame = [UIScreen mainScreen].bounds;
        [self setupSubs];
        [self reloadInitData];
    }
    return self;
}
- (void)awakeFromNib{
    [super awakeFromNib];
    self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.6];
    self.bottomView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.01];
    self.boardView.frame = CGRectMake(0, self.boardView.frame.origin.y, kHTScreenWidth, self.boardView.frame.size.height);
    self.animateTop.constant = kHTScreenHeight/6*5;
    [self setNeedsLayout];
}
//所有手势
- (void)setupGesture{
   
    //点击空白处
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
    [self.bottomView addGestureRecognizer:tap];
    //省市区
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didClickTab:)];
    self.provinceLabel.tag = 115;
    self.provinceLabel.userInteractionEnabled = YES;
    [self.provinceLabel addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didClickTab:)];
    self.cityLabel.tag = 116;
    self.cityLabel.userInteractionEnabled = YES;
    [self.cityLabel addGestureRecognizer:tap2];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didClickTab:)];
    self.areaLabel.tag = 117;
    self.areaLabel.userInteractionEnabled = YES;
    [self.areaLabel addGestureRecognizer:tap3];
}
- (void)setupSubs{
   
    //省市区圆角
    [self setCornerWith:self.provinceLabel];
    [self setCornerWith:self.cityLabel];
    [self setCornerWith:self.areaLabel];
    self.historyFirstButton.contentEdgeInsets = UIEdgeInsetsMake(4, 8, 4, 8);
    self.historySecondButton.contentEdgeInsets = UIEdgeInsetsMake(4, 8, 4, 8);
    self.historyThirdButton.contentEdgeInsets = UIEdgeInsetsMake(4, 8, 4, 8);
    [self setupGesture];
    self.topViewY.constant = kWidth(30);
    [self.flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.flowLayout.itemSize = CGSizeMake(kHTScreenWidth/4, kWidth(44));
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.minimumInteritemSpacing = 0;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HTNormalCollectionCell" bundle:nil] forCellWithReuseIdentifier:normalCollectionCell];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
}
- (void)reloadInitData{
    //历史数据
    [self reloadHistoryData];
    //设置选中状态
    self.selectedTabIndex = 0;
    //加载城市数据
    [self loadProvincesData];
    
}
#pragma mark --- delegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return  CGSizeMake(kHTScreenWidth/4, kWidth(44));
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HTNormalCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:normalCollectionCell forIndexPath:indexPath];
    cell.areaModel = self.dataSource[indexPath.row];
    return cell;
}
#pragma mark --- 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    HTAreaModel *areaModel = self.dataSource[indexPath.row];
    NSInteger currentIndex = indexPath.row;
    switch (areaModel.areaType) {
        case HTAreaTypeNo://全国、全省、全区
        {
            
            if (self.deliverPlaceChoiceType == HTDeliverPlaceChoiceTypeStart) {//出发地
                [self fixHistoryStartDataWithPlace:areaModel];
            }
            if (self.deliverPlaceChoiceType == HTDeliverPlaceChoiceTypeDestination) {//目的地
                [self fixHistoryDestinateDataWithPlace:areaModel];
            }
            if (self.delegate && [self.delegate respondsToSelector:@selector(didChoiceItemWithAreaModel:currentIndex:deliverType:)]) {
                [self.delegate didChoiceItemWithAreaModel:areaModel currentIndex:currentIndex deliverType:self.deliverPlaceChoiceType];
            }
            [self dismissView];
            
        }
            break;
        case HTAreaTypeProvince://省
        {
            self.selectedTabIndex = 1;
            [self setTabButtonIndex:0 WithTitle:areaModel.title];
            [self setTabButtonIndex:1 WithTitle:@"市"];
            [self setTabButtonIndex:2 WithTitle:@"区"];
            //加载市数据
            self.cities = [self.citiesTools loadCitiesDataWithIndex:currentIndex -1];
            self.dataSource = self.cities;
           
        }
            break;
        case HTAreaTypeDirectCity://直辖市
        {
            self.selectedTabIndex = 2;
            [self setTabButtonIndex:1 WithTitle:areaModel.title];
            //加载区数据
            self.cities =[self.citiesTools loadCitiesDataWithIndex:currentIndex - 1];
            self.areas =[self.citiesTools loadAreasDataWithIndex:currentIndex - 1];
            self.dataSource = self.areas;
            
        }
            break;
        case HTAreaTypeCity://市
        {
            self.selectedTabIndex = 2;
            [self setTabButtonIndex:1 WithTitle:areaModel.title];
            self.areas =[self.citiesTools loadAreasDataWithIndex:currentIndex - 1];
            self.dataSource = self.areas;
        }
            break;
        case HTAreaTypeArea://区
        {
            if (self.deliverPlaceChoiceType == HTDeliverPlaceChoiceTypeStart) {//出发地
                [self fixHistoryStartDataWithPlace:areaModel];
            }
            if (self.deliverPlaceChoiceType == HTDeliverPlaceChoiceTypeDestination) {//目的地
                [self fixHistoryDestinateDataWithPlace:areaModel];
            }
            if (self.delegate && [self.delegate respondsToSelector:@selector(didChoiceItemWithAreaModel:currentIndex:deliverType:)]) {
                [self.delegate didChoiceItemWithAreaModel:areaModel currentIndex:currentIndex deliverType:self.deliverPlaceChoiceType];
            }
            [self dismissView];
        }
            break;
        default:
            break;
    }
    
}

- (IBAction)didClickHistoryArea:(UIButton *)sender {
    HTAreaModel *areaModel = nil;
    if (sender == self.historyFirstButton) {
        areaModel = self.historyPlistData.firstObject;
    }else if(sender == self.historySecondButton){
        areaModel = self.historyPlistData[1];
    }else if(sender == self.historyThirdButton){
        areaModel = self.historyPlistData[2];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(didChoiceItemWithHistory:deliverType:)]) {
        [self.delegate didChoiceItemWithHistory:areaModel deliverType:self.deliverPlaceChoiceType];
    }
    [self dismissView];
}
- (void)didClickTab:(UITapGestureRecognizer *)sender {
    switch ([sender view].tag) {
        case 115://省
        {
            if (self.selectedTabIndex == 0) {
                return;
            }
            self.selectedTabIndex = 0;
            self.dataSource = self.provinces;
            
        }
            break;
        case 116://市
        {
            if (self.selectedTabIndex == 1) {
                return;
            }
            
            if ([self.provinceLabel.text isEqualToString: @"省"] && [self.cityLabel.text isEqualToString: @"市"]) {
                [HTShowUtil showMessage:@"请选择省"];
                return;
            }
            if (self.cities && self.cities.count > 0) {
                self.selectedTabIndex = 1;
                self.dataSource = self.cities;
            }
            
        }
            break;
        case 117://区
        {
            if (self.selectedTabIndex == 2) {
                return;
            }
            if ([self.cityLabel.text isEqualToString: @"市"]) {
                [HTShowUtil showMessage:@"请选择市"];
                return;
            }
            self.selectedTabIndex = 2;
            self.dataSource = self.areas;
        }
            break;
        default:
            break;
    }
}
#pragma mark --- setter & getter
//设置选择类型
- (void)setDeliverPlaceChoiceType:(HTDeliverPlaceChoiceType)deliverPlaceChoiceType{
    _deliverPlaceChoiceType = deliverPlaceChoiceType;
    if (deliverPlaceChoiceType == HTDeliverPlaceChoiceTypeStart) {
        self.titleLabel.text = @"出发地";
    }else{
        self.titleLabel.text = @"目的地";
    }
    //重新加载历史数据
    [self reloadHistoryData];
}

//设置数据
- (void)setDataSource:(NSArray<HTAreaModel *> *)dataSource{
    _dataSource = dataSource;
    [self.collectionView reloadData];
}
//设置选中的tabButton
- (void)setSelectedTabIndex:(NSInteger)selectedTabIndex{
    _selectedTabIndex = selectedTabIndex;
    switch (selectedTabIndex) {
        case 0://省
        {
            [self setSelected:YES WithLabel:self.provinceLabel];
            [self setSelected:NO WithLabel:self.cityLabel];
            [self setSelected:NO WithLabel:self.areaLabel];
        }
            break;
        case 1://市
        {
            [self setSelected:NO WithLabel:self.provinceLabel];
            [self setSelected:YES WithLabel:self.cityLabel];
            [self setSelected:NO WithLabel:self.areaLabel];
            
        }
            break;
        case 2://区
        {
            [self setSelected:NO WithLabel:self.provinceLabel];
            [self setSelected:NO WithLabel:self.cityLabel];
            [self setSelected:YES WithLabel:self.areaLabel];
            
        }
            break;
        default:
            break;
    }
}


#pragma mark --- 加载数据
//重新加载历史数据
- (void)reloadHistoryData{
    NSMutableArray *data = nil;
    if (self.deliverPlaceChoiceType == HTDeliverPlaceChoiceTypeStart) {//出发地
        data = [HTMUserDefaultUtil getHistoryStartArray];
        self.historyPlistData = data;
    }
    if (self.deliverPlaceChoiceType == HTDeliverPlaceChoiceTypeDestination) {
        data = [HTMUserDefaultUtil getHistoryDestinationArray];
        self.historyPlistData = data;
    }
    if (data == nil ||  data.count <= 0) {
        self.topHeight.constant = 1;
        self.historyView.hidden = YES;
        [self.historyView setNeedsLayout];
    }else{
        self.historyView.hidden = NO;
        self.topHeight.constant = kWidth(50);
        self.historyFirstButton.hidden = YES;
        self.historySecondButton.hidden = YES;
        self.historyThirdButton.hidden = YES;
        for (int i = 0; i < data.count; i++) {
            if (i == 0) {
                self.historyFirstButton.hidden = NO;
                [self.historyFirstButton setTitle:[(HTAreaModel *) data[i] title] forState:UIControlStateNormal];
            }
            if (i == 1) {
                self.historySecondButton.hidden = NO;
                [self.historySecondButton setTitle:[(HTAreaModel *) data[i] title] forState:UIControlStateNormal];
            }
            if (i == 2) {
                self.historyThirdButton.hidden = NO;
                [self.historyThirdButton setTitle:[(HTAreaModel *) data[i] title] forState:UIControlStateNormal];
            }
        }
    }
}
//加载全国数据
- (void)loadProvincesData{
    self.citiesTools  = [HTCitiesTools shareInstance];
    self.provinces = [self.citiesTools loadProvincesData];
    self.dataSource = self.provinces;
}
#pragma mark --- 接口
- (void)reloadAllData{
    //历史数据
    [self reloadHistoryData];
    self.selectedTabIndex = 0;
    self.provinceLabel.text = @"省";
    self.cityLabel.text = @"市";
    self.areaLabel.text = @"区";
    self.dataSource = self.provinces;
}
#pragma mark --- 工具类
//设置圆角
- (void)setCornerWith:(UILabel *)label{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:label.bounds      byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight    cornerRadii:CGSizeMake(kWidth(6), kWidth(6))];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = label.bounds;
    maskLayer.path = maskPath.CGPath;
    label.layer.mask = maskLayer;
}
//设置label状态
- (void)setSelected:(BOOL)selected WithLabel:(UILabel *)label{
    if (selected) {//选中状态
        label.backgroundColor = kBlueColor;
        label.textColor = [UIColor whiteColor];
    }else{//未选中状态
        label.backgroundColor = kBackgroundColor;
        label.textColor = [UIColor blackColor];
    }
}
//设置省市区tabButton的title
- (void)setTabButtonIndex:(NSInteger)index WithTitle:(NSString *)title{
    switch (index) {
        case 0://省
        {
            self.provinceLabel.text = title;
        }
            break;
        case 1://市
        {
            self.cityLabel.text = title;
        }
            break;
        case 2://区
        {
            self.areaLabel.text = title;
        }
            break;
        default:
            break;
    }
}

#pragma mark --- 历史数据
- (void)fixHistoryStartDataWithPlace:(HTAreaModel *)place{
    NSMutableArray *history = [HTMUserDefaultUtil getHistoryStartArray];
    if (![history containsObject:place]) {
        if (history.count >= 3) {
            [history removeObjectAtIndex:0];
        }
        [history addObject:place];
    }else{
        [history removeObject:place];
        [history addObject:place];
    }
    [HTMUserDefaultUtil saveHistoryStartArray:history];
}
- (void)fixHistoryDestinateDataWithPlace:(HTAreaModel *)place{
    NSMutableArray *history = [HTMUserDefaultUtil getHistoryDestinationArray];
    if (![history containsObject:place]) {
        if (history.count >= 3) {
            [history removeObjectAtIndex:0];
        }
        [history addObject:place];
    }else{
        [history removeObject:place];
        [history addObject:place];
    }
    [HTMUserDefaultUtil saveHistoryDestinationArray:history];
}

#pragma mark --- 显示&隐藏
-(void)showView{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:.3 animations:^{
        self.animateTop.constant = 0;
        [self layoutIfNeeded];
    }];
}
-(void)dismissView {
    self.bottomView.alpha = 0;
    [UIView animateWithDuration:.3 animations:^{
        self.animateTop.constant = kHTScreenHeight/6*5;
        self.alpha = 0;
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self removeFromSuperview];
    }];
}
- (IBAction)closeAction:(id)sender {
    [self dismissView];
}
- (void)tapGesture:(id)sender{
    [self dismissView];
}
@end
